﻿using System;
using System.IO;
using System.Net;
using System.Text;

namespace HuaXingSDK
{
    public interface IHttpPost
    {
        string Post(string url, string postdata, Encoding reqenc = null, Encoding resenc = null);
    }

    internal class HttpPost : IHttpPost
    {
        static HttpPost()
        {
            ServicePointManager.ServerCertificateValidationCallback += (p1, p2, p3, p4) => true;
            ServicePointManager.DefaultConnectionLimit = 1000;
            ServicePointManager.CheckCertificateRevocationList = false;
        }

        public string Post(string url, string postdata, Encoding reqenc = null, Encoding resenc = null)
        {
            if (string.IsNullOrEmpty(url))
                throw new ArgumentNullException(nameof(url));
            if (string.IsNullOrEmpty(postdata))
                throw new ArgumentNullException(nameof(postdata));

            var data = (reqenc ?? Encoding.UTF8).GetBytes(postdata);
            var req = WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/xml; charset= utf-8";
            req.ContentLength = data.Length;
            using (var sm = req.GetRequestStream())
            {
                sm.Write(data, 0, data.Length);
            }
            var res = req.GetResponse();
            try
            {
                using (var sm = res.GetResponseStream())
                {
                    using (var reader = new StreamReader(sm, (resenc ?? Encoding.UTF8)))
                    {
                        return reader.ReadToEnd();
                    }
                }
            }
            finally
            {
                res.Close();
            }
        }
    }
}
